// 认证诊断工具
export interface AuthDiagnostics {
  hasToken: boolean;
  tokenValid: boolean;
  networkConnected: boolean;
  serverReachable: boolean;
  lastError?: string;
  recommendations: string[];
}

export const runAuthDiagnostics = async (): Promise<AuthDiagnostics> => {
  const diagnostics: AuthDiagnostics = {
    hasToken: false,
    tokenValid: false,
    networkConnected: false,
    serverReachable: false,
    recommendations: []
  };

  try {
    // 检查是否有token
    const token = localStorage.getItem('token');
    diagnostics.hasToken = !!token;

    if (!token) {
      diagnostics.recommendations.push('请先登录获取访问令牌');
      return diagnostics;
    }

    // 检查网络连接
    diagnostics.networkConnected = navigator.onLine;
    if (!diagnostics.networkConnected) {
      diagnostics.recommendations.push('网络连接已断开，请检查网络设置');
      return diagnostics;
    }

    // 检查服务器连通性
    try {
      const response = await fetch('/api/auth/verify', {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        signal: AbortSignal.timeout(5000) // 5秒超时
      });

      diagnostics.serverReachable = true;
      diagnostics.tokenValid = response.ok;

      if (!response.ok) {
        if (response.status === 401) {
          diagnostics.lastError = 'Token已过期或无效';
          diagnostics.recommendations.push('请重新登录');
        } else if (response.status === 403) {
          diagnostics.lastError = '访问被拒绝';
          diagnostics.recommendations.push('请联系管理员检查账户状态');
        } else {
          diagnostics.lastError = `服务器错误: ${response.status}`;
          diagnostics.recommendations.push('服务器暂时不可用，请稍后重试');
        }
      }
    } catch (error: any) {
      if (error.name === 'TimeoutError') {
        diagnostics.lastError = '服务器响应超时';
        diagnostics.recommendations.push('服务器响应慢，请稍后重试或检查网络');
      } else if (error.name === 'TypeError') {
        diagnostics.lastError = '无法连接到服务器';
        diagnostics.recommendations.push('请检查网络连接和服务器状态');
      } else {
        diagnostics.lastError = error.message;
        diagnostics.recommendations.push('请刷新页面重试');
      }
    }

  } catch (error: any) {
    diagnostics.lastError = error.message;
    diagnostics.recommendations.push('发生未知错误，请刷新页面重试');
  }

  return diagnostics;
};

// 获取用户友好的错误信息
export const getFriendlyErrorMessage = (diagnostics: AuthDiagnostics): string => {
  if (!diagnostics.networkConnected) {
    return '网络连接已断开，请检查网络设置后重试';
  }

  if (!diagnostics.serverReachable) {
    return '无法连接到服务器，请检查网络连接或稍后重试';
  }

  if (!diagnostics.tokenValid) {
    return '登录状态已过期，请重新登录';
  }

  if (diagnostics.lastError) {
    return `连接出现问题：${diagnostics.lastError}`;
  }

  return '正在验证身份，请稍候...';
};
